<template>
    <!-- 腾讯音视频 -->
    <div class="rtc-video-wrapper">
        <div class="rtc__card rtc__remote">
            <div class="rtc__title">
                <i class="o-icon iconfont iconuser"></i>
                <span>用户视频</span>
            </div>
            <div class="rtc__stream" v-html="remoteStreamHtml"></div>
        </div>
        <div class="rtc__card rtc__local">
            <div class="rtc__title">
                <i class="o-icon iconfont icondoctor"></i>
                <span>医生视频</span>
            </div>
            <div class="rtc__stream" id="local_stream"></div>
        </div>
    </div>
</template>

<script>
    import TRTC from "trtc-js-sdk";
    import RTCDetect from 'rtc-detect';

    export default {
        prop: {
            source: { // 患者数据
                type: Object,
                default: () => {}
            }
        },
        data() {
            return {
                hasCamera: true, // 检测摄像头
                logId: '',
                patientId: '',
                trtcParams: {
                    userId: '', // 用户id(就是进入房间时输入的用户名字！这个不可以唯一  否则同时登陆的话会被踢出房间)
                    roomId: undefined,
                    userSig: '', // 视频秘钥
                    sdkAppId: '', // 视频 adk id
                },
                joinDetail: {},
                client: null, // 视频连接
                remoteStream: null, // 远端流
                remoteStreamHtml: '', // 动态远端流
                localStream: null, // 本地流
            }
        },
        computed: {
            getWsMsg() {
                return this.$store.state.webSocketMsg;
            },
            inquiryDetail: {
                // 问诊详情
                get() {
                    let temp = this.source || {};
                    this.patientId = temp.userId || '';
                    return temp;
                },
                set(newValue) {
                    let temp = newValue || {};
                    this.patientId = temp.userId || '';
                    return temp;
                }
            }
        },
        watch: {
            getWsMsg(data) {
                if (data && data != 'pong') {
                    let packageType = data.packageType;

                    switch (packageType) {
                        case 7: // 患者加入房间
                            this.joinDetail = data.inquiryPatientInfoResp || {};
                            this.logId = this.joinDetail.logId;
                            if (data.tencentConfig) {
                                this.trtcParams.userId = '' + data.tencentConfig.userId; //用户id
                                this.trtcParams.userSig = data.tencentConfig.sig; //视频--密钥
                                this.trtcParams.roomId = Number(data.tencentConfig.room); //房间号--加入相同房间才能聊
                                this.trtcParams.sdkAppId = data.tencentConfig.appId; //视频sdkAppId
                            }

                            if (this.joinDetail.inquiryType == '1' && data.tencentConfig && data.tencentConfig != {}) {
                                // 检查摄像头
                                /* Promise.all([this.getCamera(), this.getMic()]).then(data => {
                                    if (!data[0] || !data[1]) {
                                        this.$util.message('未检测到摄像头和麦克风设备！', 'warning')
                                    }
                                }) */
                                this.checkTRTC();
                                this.createClient(this.trtcParams.userId)
                            }
                            break;

                    }
                }
            }
        },
        destoryed() {
            this.leaveRoom();
        },
        methods: {
            getCamera() {
                return new Promise((resolve, reject) => {
                    // 获取摄像头列表
                    TRTC.getCameras().then(devices => {
                        let flag = devices && devices.length > 0;
                        resolve(flag);
                    });
                })
            },
            getMic() {
                return new Promise((resolve, reject) => {
                    // 获取麦克风列表
                    TRTC.getMicrophones().then(devices => {
                        let flag = devices && devices.length > 0;

                        resolve(flag);
                    });
                })
            },
            async checkTRTC() {
                // 初始化监测模块
                const detect = new RTCDetect();
                // 获得当前环境监测结果
                const result = await detect.getReportAsync();
                // result 包含了当前环境系统的信息，API 支持度，编解码支持度，设备相关的信息
                console.log('result is >>>>>>>>', result);
            },
            createClient(userId) {

                console.log('trtc >>>>>>', userId, this.trtcParams.roomId);

                //获取签名
                const { sdkAppId, userSig, roomId } = this.trtcParams;

                this.client = TRTC.createClient({
                    mode: 'rtc',
                    sdkAppId,
                    userId,
                    roomId,
                    userSig
                });

                // 检查摄像头
                /* Promise.all([this.getCamera(), this.getMic()]).then(data => {
                    if (!data[0] || !data[1]) {
                        this.$util.message('未检测到摄像头和麦克风设备！', 'warning')
                    }
                }) */

                //注册远程监听，要放在加入房间前--这里用了发布订阅模式
                this.subscribeStream(this.client)
                //初始化后才能加入房间
                this.joinRoom(this.client, roomId)
            },
            //加入房间
            joinRoom(client, roomId) {
                this.client.join({ roomId })
                    .catch(error => {
                        console.error('进房失败：' + error);
                    })
                    .then(() => {
                        console.log('进房成功 >>>>>>');
                        //创建本地流
                        this.createStream(this.userId)
                        //播放远端流
                        this.playStream(this.client)
                    });
            },
            //创建本地音视频流
            createStream(userId) {
                const localStream = TRTC.createStream({ userId, audio: true, video: true });
                this.localStream = localStream
                console.log('创建本地音视频流 >>>>>>', this.localStream)
                localStream.initialize().catch(error => {
                        console.error('初始化本地流失败：' + error);
                    })
                    .then(() => {
                        console.log('初始化本地流成功 >>>>>>');
                        // 创建好后才能播放 本地流播放 local_stream 是div的id
                        localStream.play('local_stream');
                        //创建好后才能发布
                        this.publishStream(localStream, this.client)
                    });
            },
            //发布本地音视频流
            publishStream(localStream, client) {
                console.log(localStream, this.client, '----------------发布本地音视频流----------------------')

                this.client.publish(localStream).catch(error => {
                        console.error('本地流发布失败：' + error);
                    })
                    .then(() => {
                        console.log('本地流发布成功 >>>>>>');
                    });
            },
            //订阅远端流--加入房间之前
            subscribeStream(client) {
                this.client.on('stream-added', event => {
                    console.log('发布本地音视频流 >>>>>>', event)

                    const remoteStream = event.stream;
                    this.remoteStream = event.stream;
                    console.log('远端流增加 >>>>>>' + remoteStream.getId());
                    //订阅远端流
                    this.client.subscribe(remoteStream);
                });
                // 监听用户退出
                this.client.on('stream-removed', event => {
                    this.remoteStream = null;
                    this.remoteHtml = '';
                    this.leaveRoom();
                    console.log('远端流退出 >>>>>>')
                });
            },
            //播放远端流
            playStream(client) {
                client.on('stream-subscribed', event => {
                    console.log('播放远端流 >>>>>>', event)
                    const remoteStream = event.stream;
                    let id = remoteStream.getId()
                    console.log('远端流订阅成功 >>>>>>', id, remoteStream);
                    // 创建远端流标签，因为id是动态的，所以动态创建，用了v-html
                    // this.remoteStream = `${'remote_stream-' + id}"  >`;
                    this.remoteStreamHtml = `<div id="${'remote_stream-' + id}"></div>`;

                    //做了dom操作 需要使用$nextTick(),否则找不到创建的标签无法进行播放
                    this.$nextTick(() => {
                        //播放
                        // remoteStream.play('remote_stream-' + id);
                        remoteStream.play(`remote_stream-${id}`); // , { objectFit: "contain" }
                    })
                });
            },
            leaveRoom() {
                this.client && this.client.leave().then(() => {
                        // 关闭摄像头
                        const videoTrack = this.localStream.getVideoTrack();
                        if (videoTrack) {
                            this.localStream.removeTrack(videoTrack)
                            // 停止采集，关闭摄像头
                            videoTrack.stop();
                        }

                        console.log('退房成功 >>>>>>')
                        // 停止本地流，关闭本地流内部的音视频播放器
                        this.localStream.stop();
                        this.remoteStream = null;
                        // 关闭本地流，释放摄像头和麦克风访问权限
                        this.localStream.close();
                        this.localStream = null;
                        this.client = null;

                        // 退房成功，可再次调用client.join重新进房开启新的通话。
                    })
                    .catch(error => {
                        console.error('退房失败：' + error);
                        // 错误不可恢复，需要刷新页面。
                    });
            }
        }
    }
</script>

<style lang="scss" src="@/style/page/vedio.scss"></style>
